package com.hnjk.cbts;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExamServerAddressHandler extends AbstractHandler {
	private static final Logger logger = LoggerFactory.getLogger(ExamServerAddressHandler.class);
	private String examServerAddress;
	private static Set<String> clientSet = new HashSet<String>();
	
	private IHandlerListener listener = null;
	
	public void setListener(IHandlerListener listener) {
		this.listener = listener;
	}
	
	public ExamServerAddressHandler(String examServerAddress) {
		this.examServerAddress = examServerAddress;
	}

	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {		
		
		response.setContentType("text/plain; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = response.getWriter();
		if(ConfigProperties.getConfig("server_url").equals(target)) {
			String clientIP = request.getRemoteAddr();
			clientSet.add(clientIP);
			logger.info("客户端:{} - 总共{}个客户端已获取机考服务地址.", request.getRemoteAddr(), clientSet.size());
	        writer.print(examServerAddress);
	        
	        // test for event
	        if(this.listener != null) {
	        	ReqEvent e = new ReqEvent();
	        	e.setClientIP(clientIP);
	        	e.setClientNum(clientSet.size());
	        	listener.clientRequest(e);
	        }
		} else {
			writer.print("wrong path");
		}
		baseRequest.setHandled(true);
	}

}
